package com.ikdong.toodle.activity;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;
import com.devspark.sidenavigation.ISideNavigationCallback;
import com.devspark.sidenavigation.SideNavigationView;
import com.google.analytics.tracking.android.EasyTracker;
import com.ikdong.toodle.R;
import com.ikdong.toodle.exception.TDException;
import com.ikdong.toodle.service.SyncService;
import com.ikdong.toodle.util.AccountManager;
import com.ikdong.toodle.util.Constant;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.os.Bundle;
import android.view.Window;
import android.widget.Toast;

public abstract class BasicActivity extends SherlockFragmentActivity implements ISideNavigationCallback {
	protected SideNavigationView sideNavigationView;
	protected IntentFilter syncFilter = new IntentFilter(Constant.SERVICE_SYNC);
	protected SyncReceiver syncReceiver = new SyncReceiver();	
	
	@Override 
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);		
        requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
	}
	
	protected void initActionBar(){
    	getSupportActionBar().setHomeButtonEnabled(true);     
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);   
        setSupportProgressBarIndeterminateVisibility(true);
	}
	
	protected void initSlideMenu(){
		sideNavigationView = (SideNavigationView) findViewById(R.id.side_navigation_view);
		if(isInstallMarket()){
			sideNavigationView.setMenuItems(R.menu.slide_menu_rate);
		}else{
			sideNavigationView.setMenuItems(R.menu.slide_menu);
		}
		
		sideNavigationView.setMenuClickCallback(this);
	}
	
	@Override
	public void onStart(){
		super.onStart();
		EasyTracker.getInstance().activityStart(this);
		initActionBar();
		initSlideMenu();
	}
	
	
	@Override
	public void onResume(){
		super.onResume();
		registerReceiver(syncReceiver, syncFilter);
		refreshSyncStatus();
	}
	
	@Override
	public void onPause(){
		super.onPause();
		unregisterReceiver(syncReceiver);
	}
	
	@Override
	public void onStop(){
		super.onStop();
		EasyTracker.getInstance().activityStop(this);
	}
	
	protected boolean refreshSyncStatus(){
		boolean flag = false;		
		ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);	    
	    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
	        if (SyncService.class.getName().equals(service.service.getClassName())) {
	        	flag = true;
	        	break;
	        }
	    }
        setSupportProgressBarIndeterminateVisibility(flag);
	    
	    return flag;
	}
	
	protected class SyncReceiver extends BroadcastReceiver {
		@Override
		public void onReceive(Context context, Intent intent) {
			if(!intent.getExtras().getBoolean(SyncService.ERROR_MESSAGE)){
				refresh();
				showToast("Synchronize successfully!");
			}else{
				showToast("Fail to synchronize!");
			}
			
			setSupportProgressBarIndeterminateVisibility(false);
		}
	}
	
	abstract void refresh();
	
	protected void handleException(TDException e){
		
	}
	
	protected void showToast(String message){
		Toast.makeText(getApplicationContext(), message, Toast.LENGTH_LONG).show();
	}
	
	@Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
	        case android.R.id.home:     
	        	sideNavigationView.toggleMenu();
	           return true;
        }
    	
        return false;
    }
	
	@Override
    public void onSideNavigationItemClick(int itemId) {
        if(R.id.navigate_menu_task==itemId){
        	Intent intent = new Intent(this,TaskListActivity.class);
        	this.startActivity(intent);
        }else if(R.id.navigate_menu_folder==itemId){
        	Intent intent = new Intent(this,FolderListActivity.class);
        	this.startActivity(intent);
        }else if(R.id.navigate_menu_sync==itemId){
        	Intent intent = new Intent(this,SyncService.class);
			startService(intent);	
			showToast(this.getString(R.string.msg_start_syn));
	        setSupportProgressBarIndeterminateVisibility(true);
        }else if(R.id.navigate_menu_logout==itemId){
        	new AccountManager(this).logout();
        	Intent intent = new Intent(this,LoginActivity.class);
        	this.startActivity(intent);
        }else if(R.id.navigate_menu_rate==itemId){
        	Intent intent = new Intent(Intent.ACTION_VIEW);
        	intent.setData(Uri.parse("market://details?id="+getPackageName()));
        	startActivity(intent);
        }
    }
	
	private boolean isInstallMarket(){
		boolean flag = true;
		try{
			getPackageManager().getApplicationInfo("com.android.vending", 0 );
		}catch(Exception e){
			flag = false;
		}
		return flag;
	}
	
	
}
